import { _ as _export_sfc, m as mpMixin, a as mixin, j as resolveEasycom, k as resolveDynamicComponent, c as createBlock, o as openBlock, w as withCtx, b as createVNode, i as index$g, r as renderSlot, P as ScrollView, n as normalizeStyle, g as createElementBlock, F as Fragment, h as renderList, f as normalizeClass, s as index$i, t as createTextVNode, u as toDisplayString } from './index-Cc4oxzDN.js';
import { _ as __easycom_4, u as uvBadgeProps } from './uv-badge.D4nY_Rjy.js';

const props = {
	props: {
		// 滑块的移动过渡时间，单位ms
		duration: {
			type: Number,
			default: 300
		},
		// tabs标签数组
		list: {
			type: Array,
			default: () => []
		},
		// 滑块颜色
		lineColor: {
			type: String,
			default: '#3c9cff'
		},
		// 菜单选择中时的样式
		activeStyle: {
			type: [String, Object],
			default: () => ({
				color: '#303133'
			})
		},
		// 菜单非选中时的样式
		inactiveStyle: {
			type: [String, Object],
			default: () => ({
				color: '#606266'
			})
		},
		// 滑块长度
		lineWidth: {
			type: [String, Number],
			default: 20
		},
		// 滑块高度
		lineHeight: {
			type: [String, Number],
			default: 3
		},
		// 滑块背景显示大小，当滑块背景设置为图片时使用
		lineBgSize: {
			type: String,
			default: 'cover'
		},
		// 菜单item的样式
		itemStyle: {
			type: [String, Object],
			default: () => ({
				height: '44px'
			})
		},
		// 菜单是否可滚动
		scrollable: {
			type: Boolean,
			default: true
		},
		// 当前选中标签的索引
		current: {
			type: [Number, String],
			default: 0
		},
		// 默认读取的键名
		keyName: {
			type: String,
			default: 'name'
		},
		...uni.$uv?.props?.tabs
	}
};

/**
	 * Tabs 标签
	 * @description tabs标签组件，在标签多的时候，可以配置为左右滑动，标签少的时候，可以禁止滑动。 该组件的一个特点是配置为滚动模式时，激活的tab会自动移动到组件的中间位置。
	 * @tutorial https://www.uvui.cn/components/tabs.html
	 * @property {Array}	list	标签数组，元素为对象，如[{name: '推荐'}]
	 * @property {String | Number}	duration			滑块移动一次所需的时间，单位秒（默认 200 ）
	 * @property {String | Object} activeStyle	菜单选择中时的样式（默认{ color: '#303133' }）
	 * @property {String | Object} inactiveStyle	菜单非选择中时的样式（默认{ color: '#606266' }）
	 * @property {String | Number} lineWidth	滑块长度（默认 20）
	 * @property {String | Number} lineHeight	滑块高度（默认 3）
	 * @property {String}	lineColor	滑块颜色（默认：'#3c9cff'）
	 * @property {String} lineBgSize	滑块背景显示大小，当滑块背景设置为图片时使用（默认 cover）
	 * @property {String | Number} itemStyle	菜单item的样式（默认 { height: '44px' }）
	 * @property {String}	scrollable	菜单是否可滚动，选项很少的时候设置为false整个tabs自动居中显示（默认：true）
	 * @property {String | Number}	current	当前选中标签的索引（默认 0 ）
	 * @property {String}	keyName	从list元素对象中读取的键名（默认 'name' ）
	 * @property {String | Number}	swierWidth			swiper的宽度（默认 '750rpx' ）
	 * @property {String | Object}	customStyle	 自定义外部样式
	 * 
	 * @event {Function(index)} change 标签改变时触发 index: 点击了第几个tab，索引从0开始
	 * @event {Function(index)} click 点击标签时触发 index: 点击了第几个tab，索引从0开始
	 * @example <uv-tabs :list="list" :is-scroll="false" :current="current" @change="change"></uv-tabs>
	 */
	const _sfc_main = {
		name: 'uv-tabs',
		emits: ['click','change'],
		mixins: [mpMixin, mixin, props],
		data() {
			return {
				firstTime: true,
				scrollLeft: 0,
				scrollViewWidth: 0,
				lineOffsetLeft: 0,
				tabsRect: {
					left: 0
				},
				innerCurrent: 0,
				moving: false,
			}
		},
		watch: {
			current: {
				immediate: true,
				handler (newValue, oldValue) {
					// 内外部值不相等时，才尝试移动滑块
					if (newValue !== this.innerCurrent) {
						this.innerCurrent = newValue;
						this.$nextTick(() => {
							this.resize();
						});
					}
				}
			},
			// list变化时，重新渲染list各项信息
			list() {
				this.$nextTick(() => {
					this.resize();
				});
			}
		},
		computed: {
			textStyle() {
				return index => {
					const style = {};
					// 取当期是否激活的样式
					const customeStyle = index == this.innerCurrent ? this.$uv.addStyle(this.activeStyle) : this.$uv
						.addStyle(
							this.inactiveStyle);
					// 如果当前菜单被禁用，则加上对应颜色，需要在此做处理，是因为nvue下，无法在style样式中通过!import覆盖标签的内联样式
					if (this.list[index].disabled) {
						style.color = '#c8c9cc';
					}
					return this.$uv.deepMerge(customeStyle, style)
				}
			},
			propsBadge() {
				return uvBadgeProps
			}
		},
		async mounted() {
			this.init();
		},
		methods: {
			setLineLeft() {
				const tabItem = this.list[this.innerCurrent];
				if (!tabItem) {
					return;
				}
				// 获取滑块该移动的位置
				let lineOffsetLeft = this.list
					.slice(0, this.innerCurrent)
					.reduce((total, curr) => total + curr.rect.width, 0);
			  // 获取下划线的数值px表示法
				let lineWidth = this.$uv.getPx(this.lineWidth);
				if (this.$uv.test.number(this.lineWidth) && this.$uv.unit) {
					lineWidth = this.$uv.getPx(`${this.lineWidth}${this.$uv.unit}`);
				}
				this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2;




			
				// 如果是第一次执行此方法，让滑块在初始化时，瞬间滑动到第一个tab item的中间
				// 这里需要一个定时器，因为在非nvue下，是直接通过style绑定过渡时间，需要等其过渡完成后，再设置为false(非第一次移动滑块)
				if (this.firstTime) {
					setTimeout(() => {
						this.firstTime = false;
					}, 20);
				}
			},
			// nvue下设置滑块的位置
			animation(x, duration = 0) {









			},
			// 点击某一个标签
			clickHandler(item, index) {
				// 因为标签可能为disabled状态，所以click是一定会发出的，但是change事件是需要可用的状态才发出
				this.$emit('click', {
					...item,
					index
				});
				// 如果disabled状态，返回
				if (item.disabled) return
				if(this.innerCurrent != index) {
					this.$emit('change', {
						...item,
						index
					});
				}
				this.innerCurrent = index;

				this.$nextTick(()=>{
					this.resize();
				});









			},
			init() {
				this.$uv.sleep().then(() => {
					this.resize();
				});
			},
			setScrollLeft() {
				// 当前活动tab的布局信息，有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
				const tabRect = this.list[this.innerCurrent];
				// 累加得到当前item到左边的距离
				const offsetLeft = this.list
					.slice(0, this.innerCurrent)
					.reduce((total, curr) => {
						return total + curr.rect.width
					}, 0);
				// 此处为屏幕宽度
				const windowWidth = this.$uv.sys().windowWidth;
				// 将活动的tabs-item移动到屏幕正中间，实际上是对scroll-view的移动
				let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect
					.right) / 2 + this.tabsRect.left / 2;
				// 这里做一个限制，限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
				scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width);
				this.scrollLeft = Math.max(0, scrollLeft);
			},
			// 获取所有标签的尺寸
			resize() {
				// 如果不存在list，则不处理
				if(this.list.length === 0) {
					return
				}
				Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
					this.tabsRect = tabsRect;
					this.scrollViewWidth = 0;
					itemRect.map((item, index) => {
						// 计算scroll-view的宽度，这里
						this.scrollViewWidth += item.width;
						// 另外计算每一个item的中心点X轴坐标
						this.list[index].rect = item;
					});
					// 获取了tabs的尺寸之后，设置滑块的位置
					this.setLineLeft();
					this.setScrollLeft();
				});
			},
			// 获取导航菜单的尺寸
			getTabsRect() {
				return new Promise(resolve => {
					this.queryRect('uv-tabs__wrapper__scroll-view').then(size => resolve(size));
				})
			},
			// 获取所有标签的尺寸
			getAllItemRect() {
				return new Promise(resolve => {
					const promiseAllArr = this.list.map((item, index) => this.queryRect(
						`uv-tabs__wrapper__nav__item-${index}`, true));
					Promise.all(promiseAllArr).then(sizes => resolve(sizes));
				})
			},
			// 获取各个标签的尺寸
			queryRect(el, item) {

				// $uvGetRect为uni-ui自带的节点查询简化方法，详见文档介绍：https://www.uvui.cn/js/getRect.html
				// 组件内部一般用this.$uvGetRect，对外的为getRect，二者功能一致，名称不同
				return new Promise(resolve => {
					this.$uvGetRect(`.${el}`).then(size => {
						resolve(size);
					});
				})











			},
		},
	};

function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_v_uni_text = index$i;
  const _component_uv_badge = resolveEasycom(resolveDynamicComponent("uv-badge"), __easycom_4);
  const _component_v_uni_view = index$g;
  const _component_v_uni_scroll_view = ScrollView;

  return (openBlock(), createBlock(_component_v_uni_view, {
    class: "uv-tabs",
    style: normalizeStyle([_ctx.$uv.addStyle(_ctx.customStyle)])
  }, {
    default: withCtx(() => [
      createVNode(_component_v_uni_view, { class: "uv-tabs__wrapper" }, {
        default: withCtx(() => [
          renderSlot(_ctx.$slots, "left", {}, undefined, true),
          createVNode(_component_v_uni_view, { class: "uv-tabs__wrapper__scroll-view-wrapper" }, {
            default: withCtx(() => [
              createVNode(_component_v_uni_scroll_view, {
                "scroll-x": _ctx.scrollable,
                "scroll-left": $data.scrollLeft,
                "scroll-with-animation": "",
                class: "uv-tabs__wrapper__scroll-view",
                "show-scrollbar": false,
                ref: "uv-tabs__wrapper__scroll-view"
              }, {
                default: withCtx(() => [
                  createVNode(_component_v_uni_view, {
                    class: "uv-tabs__wrapper__nav",
                    ref: "uv-tabs__wrapper__nav",
                    style: normalizeStyle({
							flex: _ctx.scrollable ? '' : 1
						})
                  }, {
                    default: withCtx(() => [
                      (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.list, (item, index) => {
                        return (openBlock(), createBlock(_component_v_uni_view, {
                          class: normalizeClass(["uv-tabs__wrapper__nav__item", [`uv-tabs__wrapper__nav__item-${index}`, item.disabled && 'uv-tabs__wrapper__nav__item--disabled']]),
                          key: index,
                          onClick: $event => ($options.clickHandler(item, index)),
                          ref_for: true,
                          ref: `uv-tabs__wrapper__nav__item-${index}`,
                          style: normalizeStyle([{flex: _ctx.scrollable ? '' : 1},_ctx.$uv.addStyle(_ctx.itemStyle)])
                        }, {
                          default: withCtx(() => [
                            createVNode(_component_v_uni_text, {
                              class: normalizeClass([[item.disabled && 'uv-tabs__wrapper__nav__item__text--disabled'], "uv-tabs__wrapper__nav__item__text"]),
                              style: normalizeStyle([$options.textStyle(index)])
                            }, {
                              default: withCtx(() => [
                                createTextVNode(toDisplayString(item[_ctx.keyName]), 1)
                              ]),
                              _: 2
                            }, 1032, ["class", "style"]),
                            createVNode(_component_uv_badge, {
                              show: !!(item.badge && (item.badge.show || item.badge.isDot || item.badge.value)),
                              isDot: item.badge && item.badge.isDot || $options.propsBadge.isDot,
                              value: item.badge && item.badge.value || $options.propsBadge.value,
                              max: item.badge && item.badge.max || $options.propsBadge.max,
                              type: item.badge && item.badge.type || $options.propsBadge.type,
                              showZero: item.badge && item.badge.showZero || $options.propsBadge.showZero,
                              bgColor: item.badge && item.badge.bgColor || $options.propsBadge.bgColor,
                              color: item.badge && item.badge.color || $options.propsBadge.color,
                              shape: item.badge && item.badge.shape || $options.propsBadge.shape,
                              numberType: item.badge && item.badge.numberType || $options.propsBadge.numberType,
                              inverted: item.badge && item.badge.inverted || $options.propsBadge.inverted,
                              customStyle: "margin-left: 4px;"
                            }, null, 8, ["show", "isDot", "value", "max", "type", "showZero", "bgColor", "color", "shape", "numberType", "inverted"])
                          ]),
                          _: 2
                        }, 1032, ["onClick", "style", "class"]))
                      }), 128)),
                      createVNode(_component_v_uni_view, {
                        class: "uv-tabs__wrapper__nav__line",
                        ref: "uv-tabs__wrapper__nav__line",
                        style: normalizeStyle([{
										width: _ctx.$uv.addUnit(_ctx.lineWidth),
										transform: `translate(${$data.lineOffsetLeft}px)`,
										transitionDuration: `${$data.firstTime ? 0 : _ctx.duration}ms`,
										height: $data.firstTime?0:_ctx.$uv.addUnit(_ctx.lineHeight),
										background: _ctx.lineColor,
										backgroundSize: _ctx.lineBgSize,
									}])
                      }, null, 8, ["style"])
                    ]),
                    _: 1
                  }, 8, ["style"])
                ]),
                _: 1
              }, 8, ["scroll-x", "scroll-left"])
            ]),
            _: 1
          }),
          renderSlot(_ctx.$slots, "right", {}, undefined, true)
        ]),
        _: 3
      })
    ]),
    _: 3
  }, 8, ["style"]))
}
const __easycom_1 = /*#__PURE__*/_export_sfc(_sfc_main, [['render',_sfc_render],['__scopeId',"data-v-02da80e0"]]);

export { __easycom_1 as _ };
